

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <dirent.h>
#include <sys/stat.h>

#include "dir.h"

#define MAX_PATH 1024

int dir_scan(const char *path, int (*callback)(const char *path))
{
	assert(!!path);
	assert(!!callback);
	DIR *dp;
	if(!(dp=opendir(path))){
		perror("opendir");
		assert(0);
	}
	struct dirent *entry;
	while(!!(entry=readdir(dp))){
		if(entry->d_name[0]=='.'){
			continue;
		}
		char buffer[MAX_PATH];
		sprintf(buffer, "%s/%s", path, entry->d_name);
		switch(entry->d_type){
		case DT_REG:
			callback(buffer);
			break;
		case DT_DIR:
			dir_scan(buffer, callback);
			break;
		case 0:
			/* for reiserfs only*/
			if(isdir(buffer)){
				dir_scan(buffer, callback);
			}else{
				callback(buffer);
			}
			break;
		default:
			;
		}
	}
	closedir(dp);
	return 0;
}

int isdir(const char *path) 
{ 
	assert(!!path);
    struct stat stbuf; 
	
    if(lstat(path, &stbuf) < 0){ 
        perror("lstat");
		assert(0);
    } 
    return (S_ISDIR(stbuf.st_mode))?1:0; 
} 


